// v-draggable: 弹窗拖拽属性
const Draggable = {
	bind: (el, binding, vnode, oldVnode) => {
		let element = el;
		let domElement = el;
		if (el.getAttribute("class") && el.getAttribute("class").includes("dialog")) {
			element = el.querySelector(".el-dialog__header");
			domElement = el.querySelector(".el-dialog");
		}
		element.style.cssText += ";cursor:move;";
		domElement.style.cssText += ";top:0px;";
		// 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
		const style = (() => {
			if (document.currentStyle) {
				return (dom, attr, axis = "") => {
					if (axis.toUpperCase() === "X") {
						return +document.body.clientWidth * (+dom.currentStyle[attr].replace(/%/g, "") / 100);
					} else if (axis.toUpperCase() === "Y") {
						return +document.body.clientHeight * (+dom.currentStyle[attr].replace(/%/g, "") / 100);
					}
				};
			} else {
				return (dom, attr, axis) => +window.getComputedStyle(dom, false)[attr].replace(/px/g, "");
			}
		})();
		element.onmousedown = (e) => {
			// 鼠标按下，计算当前元素距离可视区的距离
			const distanceX = e.clientX - element.offsetLeft;
			const distanceY = e.clientY - element.offsetTop;
			const minLeft = domElement.offsetLeft;
			const minTop = domElement.offsetTop;
			const maxLeft = document.body.clientWidth - domElement.offsetLeft - domElement.offsetWidth;
			const maxTop = document.body.clientHeight - domElement.offsetTop - domElement.offsetHeight;
			// 获取到的值带px 正则匹配替换
			let styleLeft = style(domElement, "left", "X");
			let styleTop = style(domElement, "top", "Y");
			document.onmousemove = (e) => {
				// 通过事件委托，计算移动的距离
				let left = e.clientX - distanceX;
				let top = e.clientY - distanceY;
				// 边界处理
				if (-(left) > minLeft) {
					left = -(minLeft);
				} else if (left > maxLeft) {
					left = maxLeft;
				}
				if (-(top) > minTop) {
					top = -(minTop);
				} else if (top > maxTop) {
					top = maxTop;
				}
				// 移动当前元素
				domElement.style.cssText += `;left:${left + styleLeft}px;top:${top + styleTop}px;`;
			};
			document.onmouseup = () => {
				document.onmousemove = document.onmouseup = null;
			};
		};
	}
};
export default Draggable;
